package com.song.su.provider;
/*
* 提供者，提供所必须的类来实现一些访问的方法
* 实现发送post请求数据
* */

import com.alibaba.fastjson.JSON;
import com.song.su.dto.AccessTokenDTO;
import com.song.su.dto.GithubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;



//调用github api post 发送code ,封装githubprovider
@Component // 快速调用类，依赖注入
public class GithubProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        // 将accessTokenDTO 转换为json格式 使用fastjson
        RequestBody body = RequestBody.create(JSON.toJSONString(accessTokenDTO), mediaType);
        Request request = new Request.Builder()
                    .url("https://github.com/login/oauth/access_token")
                    .post(body)
                    .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
//           返回切割 string = access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer
            String split = string.split("&")[0].split("=")[1];
            System.out.println(split);
                return split;
            } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public GithubUser getUser(String accessToken) throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://api.github.com/user")
                .header("Authorization","token "+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String  string = response.body().string();
//            System.out.println(string);
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
//            System.out.println(githubUser.getId());
            return githubUser;

        }catch ( IOException e){
            return null;
        }

    }

}
